/*动态计算表格高度*/
import { nextTick, onBeforeUnmount, onMounted, Ref, ref } from 'vue';

export function useTableHeight(cardRef: Ref<any>, otherRefs: Ref<any>[]) {
  const tableHeight = ref(0);

  const calculateTableHeight = () => {
    const cardElement = cardRef.value?.$el || cardRef.value;
    if (cardElement instanceof HTMLElement) {
      let otherHeight = 0;
      otherRefs.forEach((ref) => {
        const element = ref.value?.$el || ref.value;
        if (element instanceof HTMLElement) {
          otherHeight += element.getBoundingClientRect().height;
        }
      });
      const cardRect = cardElement.getBoundingClientRect();
      const windowHeight = window.innerHeight;
      if (otherHeight !== 0) {
        otherHeight = otherHeight + 22;
      }
      tableHeight.value = windowHeight - cardRect.top - otherHeight - 40 - 80;
    } else {
      console.warn('cardElement is not an HTMLElement');
    }
  };

  let resizeObserver: ResizeObserver | null = null;

  onMounted(async () => {
    await nextTick(); // 等待 DOM 更新
    calculateTableHeight();
    window.addEventListener('resize', calculateTableHeight);

    // 监听 cardRef 的高度变化
    const cardElement = cardRef.value?.$el || cardRef.value;
    if (cardElement instanceof HTMLElement) {
      resizeObserver = new ResizeObserver(calculateTableHeight);
      resizeObserver.observe(cardElement);
    }
  });

  onBeforeUnmount(() => {
    window.removeEventListener('resize', calculateTableHeight);
    if (resizeObserver) {
      const cardElement = cardRef.value?.$el || cardRef.value;
      if (cardElement instanceof HTMLElement) {
        resizeObserver.unobserve(cardElement);
      }
      resizeObserver.disconnect();
    }
  });

  return {
    tableHeight
  };
}
